<?php

namespace App\Repositories\Permission;

use App\Models\Permission;
use App\Repositories\BaseRepository;

class PermissionRepository extends BaseRepository
{
    public function __construct(Permission $model)
    {
        parent::__construct($model);
    }

    public function getPermissions(): array
    {
        $transform = function ($row) use (&$transform) {
            return [
                'title' => $row->title,
                'icon' => $row->icon,
                'name' => $row->name,
                'active' => $row->active,
                'redirect' => $row->redirect,
                'children' => $row->children->map($transform)->toArray()
            ];
        };

        $query = Permission::query()->with('children')->where('status', 1)->where('parent_id',0);
        return $query->orderBy('sort')
            ->get()
            ->map($transform)
            ->toArray();
    }

    public function tree(): array
    {
        $transform = function ($row) use (&$transform) {
            return [
                'id' => $row->id,
                'parent_id' => $row->parent_id,
                'title' => $row->title,
                'icon' => $row->icon,
                'name' => $row->name,
                'active' => $row->active,
                'redirect' => $row->redirect,
                'type' => $row->type,
                'is_show' => $row->is_show,
                'slug' => $row->slug,
                'sort' => $row->sort,
                'status' => $row->status,
                'created_at' => $row->created_at ? $row->created_at->format('Y-m-d') : null,
                'children' => $row->children->map($transform)->toArray()
            ];
        };

        $query = Permission::query()->with('children')->where('parent_id',0);
        return $query->orderBy('sort')
            ->get()
            ->map($transform)
            ->toArray();
    }

    public function getSelect(): array
    {
        $transform = function ($row) use (&$transform) {
            return [
                'id' => $row->id,
                'parent_id' => $row->parent_id,
                'title' => $row->title,
                'children' => $row->children->map($transform)->toArray()
            ];
        };
        return Permission::query()->with('children')->where('status', 1)->where('parent_id',0)
            ->get(['id','title','parent_id']) ->map($transform)
            ->toArray();
    }
}

